#import "UnixScript.h"
#import "FileName.h"
#import "support.h"
#import "EnhancedApp.h"
#include <sys/file.h>

const char *TAR_COMMAND = "tar chf - * | compress > ";
const char *SCRIPT_HEADER = "\n#BEGIN_HERE \n\
# This shell script unpacks a uuencoded, compressed, tar file. \n\
# You can run it in one of two ways: \n\
#	1) save the entire text to a file and then: \n\
#		awk \"/^#BEGIN_HERE/,/^exit/\" < file | /bin/sh \n\
#	2) Or, remove everything before #BEGIN_HERE, save to file and then: \n\
#		/bin/sh < file \n\
if test -d attachments \n\
then \n\
  echo \"An attachments directory exits. Remove, rename or move it.\" \n\
else \n\
mkdir attachments; cd attachments \n\
uudecode << \\ALL_DONE\n";

const char *SCRIPT_TRAILER = "ALL_DONE\n\
zcat .attach.Z | tar xf - \n\
rm .attach.Z \n\
fi \n\
exit 0 \n";

@implementation UnixScript

- initForMUA: (const char *)anApp  andMTA: (const char *)aMailer
{
   [super initForMUA: anApp andMTA: aMailer];
   tmpDir = [[StringStorage alloc] init:"/tmp/.attachments"];
   [tmpDir mktemp];
   mkdir([tmpDir stringValue],0700);
   attachFile = [[StringStorage alloc] init: [tmpDir stringValue]];
   [attachFile appendStringValue: ".attach.Z"];
   return self;
}

- free
{
   int x, cnt;

   unlink([attachFile stringValue]);	     /* unlink the compressed tar file */

   chdir([tmpDir stringValue]);		     /* clean up the enclosure directory */

   for(x = 0, cnt = [attachments count]; x < cnt; x++)
       unlink([[attachments objectAt: x] basename]);

   chdir([NXApp appDirectory]);
   rmdir([tmpDir stringValue]);		     /* remove it */

   [tmpDir free];
   [attachFile free];
   return [super free];
}

- buildBody
{
   char tarCmd[FILENAME_MAX + 30];
   int x, cnt;
   id aFile;

   [super buildBody];
   
   fwrite(SCRIPT_HEADER,1,strlen(SCRIPT_HEADER), fp);

   chdir([tmpDir stringValue]);
   for(x = 0, cnt = [attachments count]; x < cnt; x++)
   {
      aFile = [attachments objectAt: x];
      symlink([aFile stringValue],[aFile basename]);
   }

   strcpy(tarCmd, TAR_COMMAND);
   strcat(tarCmd, [attachFile stringValue]);
   system(tarCmd);
   uuencode(".attach.Z", [attachFile stringValue], fp, 0666);
   fwrite(SCRIPT_TRAILER,1,strlen(SCRIPT_TRAILER),fp);
   return self;
}

+ (BOOL)supportsAttachments
{
   return YES;
}

@end
